<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

// 验证用户是否登录
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

// 当前用户
$currentUser = $_SESSION['username'];

// 获取用户头像
function getUserAvatar($username) {
    $userDir = __DIR__ . "/user/$username";
    if (!is_dir($userDir)) return null;
    
    $avatarFiles = scandir($userDir);
    foreach ($avatarFiles as $file) {
        if ($file === '.' || $file === '..') continue;
        
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, ['png', 'jpg', 'jpeg', 'gif'])) {
            return "user/$username/$file";
        }
    }
    return null;
}

$userAvatar = getUserAvatar($currentUser);

// 确保文件存在
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        $dir = dirname($filename);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

// 公共聊天文件路径
$publicChatFile = __DIR__ . "/messages/public_chat.json";
$messages = ensureFile($publicChatFile);

// 处理 AJAX 请求以发送消息
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $rawMessage = trim($_POST['message']);
    
    // 基本安全过滤
    $message = strip_tags($rawMessage); // 移除所有HTML标签
    $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); // 转义特殊字符
    
    // 验证消息长度
    if (mb_strlen($message) === 0) {
        echo json_encode(['status' => 'error', 'message' => '消息不能为空']);
        exit();
    }
    
    if (mb_strlen($message) > 500) {
        echo json_encode(['status' => 'error', 'message' => '消息不能超过500个字符']);
        exit();
    }
    
    // 生成唯一消息ID
    $messageId = uniqid();
    
    $newMessage = [
        'id' => $messageId,
        'user' => $currentUser,
        'content' => $message,
        'timestamp' => date('Y-m-d H:i:s'),
        'status' => 'sending',
        'avatar' => $userAvatar
    ];
    
    $messages[] = $newMessage;
    file_put_contents($publicChatFile, json_encode($messages));
    
    // 模拟发送延迟
    sleep(1);
    
    // 更新消息状态为已发送
    $lastIndex = count($messages) - 1;
    $messages[$lastIndex]['status'] = 'sent';
    file_put_contents($publicChatFile, json_encode($messages));
    
    echo json_encode([
        'status' => 'success', 
        'message' => '消息发送成功',
        'message_id' => $messageId
    ]);
    exit();
}

// 返回聊天内容的 AJAX 请求
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['fetch_messages'])) {
    $lastId = $_GET['last_id'] ?? '';
    $newMessages = [];
    
    if ($lastId) {
        $found = false;
        foreach ($messages as $msg) {
            if ($found) {
                $newMessages[] = $msg;
            }
            if (isset($msg['id']) && $msg['id'] === $lastId) {
                $found = true;
            }
        }
    } else {
        $newMessages = $messages;
    }
    
    // 为每条消息添加头像信息
    $messagesWithAvatars = [];
    foreach ($newMessages as $msg) {
        if (!isset($msg['avatar'])) {
            $msg['avatar'] = getUserAvatar($msg['user']);
        }
        $messagesWithAvatars[] = $msg;
    }
    
    // 获取最后一条消息ID
    $lastMessageId = count($messages) > 0 ? $messages[count($messages)-1]['id'] : '';
    
    echo json_encode([
        'messages' => $messagesWithAvatars,
        'last_id' => $lastMessageId
    ]);
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>公共聊天 - JIILCHAT</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            height: 100vh;
            overflow: hidden;
        }
        
        /* 顶部导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #ffffff;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            z-index: 100;
            border-bottom: 1px solid #e0e4e9;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000;
            font-size: 20px;
            margin-right: 10px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #e4e6eb;
        }
        
        .navbar-title {
            font-size: 17px;
            font-weight: 600;
            flex-grow: 1;
            color: #333;
        }
        
        /* 聊天容器 */
        .chat-container {
            margin-top: 60px;
            padding: 15px;
            height: calc(100vh - 130px);
            overflow-y: auto;
            scroll-behavior: smooth;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }
        
        /* 消息样式 */
        .message {
            max-width: 85%;
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 18px;
            position: relative;
            animation: fadeIn 0.3s ease-out;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .message.other {
            align-self: flex-start;
            background: white;
            border-bottom-left-radius: 5px;
        }
        
        .message.self {
            align-self: flex-end;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }
        
        .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 10px;
            background: #e0e4e9;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #7f8c8d;
            font-weight: bold;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .user-avatar:hover {
            transform: scale(1.05);
        }
        
        .user-name {
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            color: #3498db;
        }
        
        .user-name:hover {
            text-decoration: underline;
        }
        
        .message.self .user-name {
            color: rgba(255,255,255,0.9);
        }
        
        .message-content {
            font-size: 15px;
            line-height: 1.5;
            word-break: break-word;
        }
        
        .message-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 8px;
            font-size: 12px;
            opacity: 0.8;
        }
        
        .message.self .message-footer {
            color: rgba(255,255,255,0.8);
        }
        
        .message-status {
            display: flex;
            align-items: center;
        }
        
        .status-icon {
            margin-left: 5px;
            font-size: 14px;
        }
        
        .status-sending {
            color: #7f8c8d;
            animation: spin 1s linear infinite;
        }
        
        .status-sent {
            color: #2ecc71;
        }
        
        .status-error {
            color: #e74c3c;
            cursor: pointer;
        }
        
        /* 输入区域 */
        .input-container {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            padding: 15px;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            z-index: 100;
            border-top: 1px solid #e9ecef;
        }
        
        .input-wrapper {
            display: flex;
            align-items: flex-end;
            gap: 10px;
        }
        
        .message-input {
            flex-grow: 1;
            padding: 14px;
            border: 1px solid #e9ecef;
            border-radius: 25px;
            font-size: 15px;
            resize: none;
            max-height: 150px;
            min-height: 50px;
            transition: all 0.3s ease;
        }
        
        .message-input:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .emoji-btn {
            background: #f8f9fa;
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .emoji-btn:hover {
            background: #e9ecef;
        }
        
        .send-btn {
            background: #3498db;
            color: white;
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .send-btn:hover {
            background: #2980b9;
            transform: scale(1.05);
        }
        
        .send-btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            transform: none;
        }
        
        .error-message {
            color: #e74c3c;
            font-size: 13px;
            margin-top: 8px;
            text-align: center;
            display: none;
        }
        
        /* 表情面板 */
        .emoji-panel {
            position: absolute;
            bottom: 70px;
            right: 15px;
            background: white;
            border-radius: 16px;
            padding: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
            display: none;
            flex-wrap: wrap;
            gap: 8px;
            width: 300px;
            max-height: 250px;
            overflow-y: auto;
            z-index: 200;
        }
        
        .emoji-panel.active {
            display: flex;
        }
        
        .emoji-item {
            font-size: 24px;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.2s ease;
        }
        
        .emoji-item:hover {
            background: #f0f7ff;
            transform: scale(1.1);
        }
        
        /* 滚动到底部按钮 */
        .scroll-bottom-btn {
            position: fixed;
            bottom: 80px;
            right: 20px;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            background: #3498db;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 90;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s ease;
        }
        
        .scroll-bottom-btn.visible {
            opacity: 1;
            transform: translateY(0);
        }
        
        .scroll-bottom-btn:hover {
            background: #2980b9;
            transform: translateY(-3px);
        }
        
        /* 动画 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #7f8c8d;
        }
        
        .empty-state i {
            font-size: 48px;
            opacity: 0.3;
            margin-bottom: 15px;
        }
        
        /* 加载指示器 */
        .loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 300;
            flex-direction: column;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid rgba(52, 152, 219, 0.2);
            border-top: 5px solid #3498db;
            border-radius: 50%;
            animation: spin 1.5s linear infinite;
            margin-bottom: 25px;
        }
        
        .loading-text {
            font-size: 24px;
            font-weight: 600;
            color: #2d3748;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 0.5; transform: scale(1); }
            50% { opacity: 1; transform: scale(1.05); }
            100% { opacity: 0.5; transform: scale(1); }
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .message {
                max-width: 90%;
            }
            
            .emoji-panel {
                width: 100%;
                right: 0;
                border-radius: 0;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="navbar">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="navbar-title">公共聊天室</div>
    </div>
    
    <!-- 聊天容器 -->
    <div class="chat-container" id="chat-container">
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <div class="loading-text">正在加载消息...</div>
        </div>
    </div>
    
    <!-- 滚动到底部按钮 -->
    <div class="scroll-bottom-btn" id="scroll-bottom-btn">
        <i class="fas fa-arrow-down"></i>
    </div>
    
    <!-- 输入区域 -->
    <div class="input-container">
        <div class="emoji-panel" id="emoji-panel">
            <!-- 表情将由JavaScript生成 -->
        </div>
        
        <div class="input-wrapper">
            <textarea class="message-input" id="message-input" placeholder="输入消息..." rows="1"></textarea>
            
            <button class="emoji-btn" id="emoji-btn">
                <i class="far fa-smile"></i>
            </button>
            
            <button class="send-btn" id="send-btn" disabled>
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
        
        <div class="error-message" id="error-message"></div>
    </div>
    
    <script>
        // 当前用户
        const currentUser = "<?= $currentUser ?>";
        
        // DOM元素
        const chatContainer = document.getElementById('chat-container');
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const emojiBtn = document.getElementById('emoji-btn');
        const emojiPanel = document.getElementById('emoji-panel');
        const scrollBottomBtn = document.getElementById('scroll-bottom-btn');
        const errorMessage = document.getElementById('error-message');
        const loadingIndicator = document.getElementById('loading');
        
        // 状态变量
        let isAtBottom = true;
        let isSending = false;
        let emojiPanelOpen = false;
        let lastMessageId = '';
        let renderedMessageIds = new Set();
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化表情面板
            initEmojiPanel();
            
            // 加载消息
            fetchMessages();
            
            // 滚动到底部
            scrollToBottom();
            
            // 设置输入框事件
            messageInput.addEventListener('input', handleInputChange);
            messageInput.addEventListener('keydown', handleKeyDown);
            
            // 设置发送按钮事件
            sendBtn.addEventListener('click', sendMessage);
            
            // 设置表情按钮事件
            emojiBtn.addEventListener('click', toggleEmojiPanel);
            
            // 设置滚动事件
            chatContainer.addEventListener('scroll', handleScroll);
            
            // 设置滚动到底部按钮事件
            scrollBottomBtn.addEventListener('click', scrollToBottom);
            
            // 设置点击外部关闭表情面板
            document.addEventListener('click', function(e) {
                if (emojiPanelOpen && !emojiBtn.contains(e.target) && !emojiPanel.contains(e.target)) {
                    closeEmojiPanel();
                }
            });
            
            // 启动消息轮询
            startMessagePolling();
        });
        
        // 初始化表情面板
        function initEmojiPanel() {
            const EMOJIS = [
                "😀", "😃", "😄", "😁", "😆", "😅", "😂", "🤣", "😊", "😇",
                "🙂", "🙃", "😉", "😌", "😍", "🥰", "😘", "😗", "😙", "😚",
                "😋", "😛", "😝", "😜", "🤪", "🤨", "🧐", "🤓", "😎", "🤩",
                "🥳", "😏", "😒", "😞", "😔", "😟", "😕", "🙁", "☹️", "😣",
                "😖", "😫", "😩", "🥺", "😢", "😭", "😤", "😠", "😡", "🤬",
                "🤯", "😳", "🥵", "🥶", "😱", "😨", "😰", "😥", "😓", "🫣",
                "🤗", "🫡", "🤔", "🫢", "🤭", "🤫", "🤥", "😶", "🫠", "😑",
                "🫤", "😒", "🙄", "😬", "😮‍💨", "🤤", "😪", "😮", "😯", "😲",
                "🥱", "😵", "😵‍💫", "🤐", "🥴", "🤢", "🤮", "🤧", "😷", "🤒",
                "🤕", "🤑", "😈", "👿", "👹", "👺", "🤡", "💩", "👻", "💀",
                "☠️", "👽", "👾", "🤖", "🎃", "😺", "😸", "😹", "😻", "😼",
                "😽", "🙀", "😿", "😾", "❤️", "💘", "💝", "💖", "💗", "💕",
                "💞", "💓", "💔", "💋", "💐", "🌹", "🥀", "🌷", "🌼", "🌸",
                "🌺", "🌻", "🍕", "🍔", "🍟", "🍗", "🌭", "🍿", "🍦", "🍨",
                "🍩", "🍪", "🎂", "🍰", "🍫", "☕", "🍺", "🍷", "🍾", "🍹"
            ];
            
            emojiPanel.innerHTML = '';
            EMOJIS.forEach(emoji => {
                const emojiItem = document.createElement('div');
                emojiItem.className = 'emoji-item';
                emojiItem.textContent = emoji;
                emojiItem.addEventListener('click', () => insertEmoji(emoji));
                emojiPanel.appendChild(emojiItem);
            });
        }
        
        // 处理输入变化
        function handleInputChange() {
            // 调整输入框高度
            messageInput.style.height = 'auto';
            messageInput.style.height = Math.min(messageInput.scrollHeight, 150) + 'px';
            
            // 启用/禁用发送按钮
            sendBtn.disabled = messageInput.value.trim() === '';
        }
        
        // 处理键盘事件
        function handleKeyDown(e) {
            // 按Enter键发送消息（不换行）
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!sendBtn.disabled) {
                    sendMessage();
                }
            }
        }
        
        // 切换表情面板
        function toggleEmojiPanel() {
            emojiPanelOpen = !emojiPanelOpen;
            emojiPanel.classList.toggle('active', emojiPanelOpen);
        }
        
        // 关闭表情面板
        function closeEmojiPanel() {
            emojiPanelOpen = false;
            emojiPanel.classList.remove('active');
        }
        
        // 插入表情
        function insertEmoji(emoji) {
            messageInput.value += emoji;
            handleInputChange();
            closeEmojiPanel();
            messageInput.focus();
        }
        
        // 处理滚动事件
        function handleScroll() {
            // 检查是否在底部
            const isNearBottom = chatContainer.scrollTop + chatContainer.clientHeight >= chatContainer.scrollHeight - 50;
            isAtBottom = isNearBottom;
            
            // 显示/隐藏滚动到底部按钮
            scrollBottomBtn.classList.toggle('visible', !isAtBottom);
        }
        
        // 滚动到底部
        function scrollToBottom() {
            chatContainer.scrollTop = chatContainer.scrollHeight;
            isAtBottom = true;
            scrollBottomBtn.classList.remove('visible');
        }
        
        // 启动消息轮询
        function startMessagePolling() {
            // 每3秒获取一次新消息
            setInterval(fetchMessages, 3000);
        }
        
        // 获取消息
        function fetchMessages() {
            const params = new URLSearchParams();
            params.append('fetch_messages', true);
            
            // 添加最后一条消息ID
            if (lastMessageId) {
                params.append('last_id', lastMessageId);
            }
            
            fetch(`public.php?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    // 更新最后一条消息ID
                    if (data.last_id) {
                        lastMessageId = data.last_id;
                    }
                    
                    // 渲染新消息
                    if (data.messages && data.messages.length > 0) {
                        renderMessages(data.messages);
                    }
                    
                    // 如果用户在最底部，自动滚动
                    if (isAtBottom) {
                        scrollToBottom();
                    }
                    
                    // 隐藏加载指示器
                    loadingIndicator.style.display = 'none';
                })
                .catch(error => {
                    console.error('获取消息失败:', error);
                    loadingIndicator.querySelector('.loading-text').textContent = '加载消息失败，请重试';
                });
        }
        
        // 渲染消息
        function renderMessages(messages) {
            if (messages.length === 0) {
                chatContainer.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-comments"></i>
                        <h3>欢迎来到公共聊天室</h3>
                        <p>发送第一条消息开始聊天吧！</p>
                    </div>
                `;
                return;
            }
            
            // 创建文档片段
            const fragment = document.createDocumentFragment();
            let hasNewMessages = false;
            
            messages.forEach(msg => {
                // 检查是否已经渲染过
                if (renderedMessageIds.has(msg.id)) return;
                
                // 添加到已渲染集合
                renderedMessageIds.add(msg.id);
                hasNewMessages = true;
                
                // 创建消息元素
                const messageElement = createMessageElement(msg);
                messageElement.classList.add('new-message');
                
                // 添加到文档片段
                fragment.appendChild(messageElement);
            });
            
            // 如果有新消息，添加到聊天容器
            if (hasNewMessages) {
                chatContainer.appendChild(fragment);
                
                // 如果用户在最底部，自动滚动
                if (isAtBottom) {
                    scrollToBottom();
                }
            }
        }
        
        // 创建消息元素
        function createMessageElement(msg) {
            const isSelf = msg.user === currentUser;
            const avatar = msg.avatar || '';
            const avatarLetter = msg.user.charAt(0).toUpperCase();
            const statusIcon = getStatusIcon(msg.status);
            
            const messageElement = document.createElement('div');
            messageElement.className = `message ${isSelf ? 'self' : 'other'}`;
            messageElement.dataset.messageId = msg.id;
            messageElement.innerHTML = `
                <div class="message-header">
                    ${avatar ? 
                        `<img src="${avatar}" alt="头像" class="user-avatar" onclick="viewUser('${msg.user}')">` : 
                        `<div class="user-avatar" onclick="viewUser('${msg.user}')">${avatarLetter}</div>`
                    }
                    <div class="user-name" onclick="viewUser('${msg.user}')">${msg.user}</div>
                </div>
                <div class="message-content">${msg.content}</div>
                <div class="message-footer">
                    <div class="message-time">${formatTime(msg.timestamp)}</div>
                    <div class="message-status">
                        ${statusIcon}
                    </div>
                </div>
            `;
            
            // 添加重试事件
            if (msg.status === 'error') {
                const statusIcon = messageElement.querySelector('.status-error');
                if (statusIcon) {
                    statusIcon.addEventListener('click', function() {
                        // 重新发送消息
                        const content = messageElement.querySelector('.message-content').textContent;
                        messageInput.value = content;
                        handleInputChange();
                        sendMessage();
                        messageElement.remove();
                    });
                }
            }
            
            return messageElement;
        }
        
        // 获取状态图标
        function getStatusIcon(status) {
            switch (status) {
                case 'sending':
                    return '<i class="fas fa-circle-notch fa-spin status-icon status-sending"></i>';
                case 'sent':
                    return '<i class="fas fa-check-circle status-icon status-sent"></i>';
                case 'error':
                    return '<i class="fas fa-exclamation-circle status-icon status-error" title="发送失败，点击重试"></i>';
                default:
                    return '';
            }
        }
        
        // 格式化时间
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            const now = new Date();
            
            // 如果是今天，显示时间
            if (date.toDateString() === now.toDateString()) {
                return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            }
            
            // 否则显示日期
            return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
        }
        
        // 发送消息
        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || isSending) return;
            
            // 清空错误消息
            errorMessage.style.display = 'none';
            errorMessage.textContent = '';
            
            // 禁用输入和发送按钮
            isSending = true;
            messageInput.disabled = true;
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            
            // 创建临时消息
            const tempId = 'temp_' + Date.now();
            const tempMessage = {
                id: tempId,
                user: currentUser,
                content: message,
                timestamp: new Date().toISOString(),
                status: 'sending',
                avatar: "<?= $userAvatar ?>"
            };
            
            // 添加到已渲染集合
            renderedMessageIds.add(tempId);
            
            // 创建临时消息元素
            const tempMessageElement = createMessageElement(tempMessage);
            chatContainer.appendChild(tempMessageElement);
            scrollToBottom();
            
            // 发送请求
            fetch('public.php', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `message=${encodeURIComponent(message)}`
            })
            .then(response => response.json())
            .then(result => {
                if (result.status === 'success') {
                    // 更新消息状态
                    tempMessage.status = 'sent';
                    updateMessageStatus(tempMessageElement, 'sent');
                    
                    // 更新消息ID
                    if (result.message_id) {
                        // 从已渲染集合中移除临时ID
                        renderedMessageIds.delete(tempId);
                        
                        // 添加新ID
                        renderedMessageIds.add(result.message_id);
                        
                        // 更新元素ID
                        tempMessageElement.dataset.messageId = result.message_id;
                    }
                    
                    // 清空输入框
                    messageInput.value = '';
                    handleInputChange();
                } else {
                    // 显示错误
                    tempMessage.status = 'error';
                    updateMessageStatus(tempMessageElement, 'error');
                    showError(result.message);
                }
            })
            .catch(error => {
                // 显示错误
                tempMessage.status = 'error';
                updateMessageStatus(tempMessageElement, 'error');
                showError('发送失败，请重试');
            })
            .finally(() => {
                // 启用输入和发送按钮
                isSending = false;
                messageInput.disabled = false;
                sendBtn.disabled = false;
                sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
                
                // 立即获取新消息
                fetchMessages();
            });
        }
        
        // 更新消息状态
        function updateMessageStatus(element, status) {
            const statusContainer = element.querySelector('.message-status');
            if (statusContainer) {
                statusContainer.innerHTML = getStatusIcon(status);
                
                // 添加重试事件
                if (status === 'error') {
                    const statusIcon = statusContainer.querySelector('.status-error');
                    if (statusIcon) {
                        statusIcon.addEventListener('click', function() {
                            // 重新发送消息
                            const content = element.querySelector('.message-content').textContent;
                            messageInput.value = content;
                            handleInputChange();
                            sendMessage();
                            element.remove();
                        });
                    }
                }
            }
        }
        
        // 显示错误消息
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
        }
        
        // 查看用户
        function viewUser(username) {
            window.location.href = `userinfo.php?user=${encodeURIComponent(username)}`;
        }
    </script>
</body>
</html>